package com.laputacastle.dr.minio;

import io.minio.MinioClient;
import io.minio.messages.Bucket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

@Component
public class MinioUtil {
	protected static final Logger logger = LoggerFactory.getLogger(MinioUtil.class);

	@Autowired
	private MinioConnect minioConnect;
	/**
	 * 获取minio连接
	 *
	 * @return client
	 */
	private MinioClient getClient() {
		return minioConnect.getClient();
	}

	public void listBuckets() {
		try {
			// 列出所有存储桶
			List<Bucket> bucketList = getClient().listBuckets();
			for (Bucket bucket : bucketList) {
			    logger.info(bucket.creationDate() + ", " + bucket.name());
			}
		} catch (Exception e) {
		    logger.error("Error occurred: ", e);
		}
	}

	/**
	 * 上传文件
	 * @param bucketName 桶名
	 * @param fileName 文件名
	 * @param stream 文件流
	 */
	public String uploadFile(String bucketName, String fileName, InputStream stream) {
		try {
			if (!getClient().bucketExists(bucketName)) {
				getClient().makeBucket(bucketName);
			}
			getClient().putObject(bucketName, fileName, stream, "application/octet-stream");
			return getClient().presignedGetObject(bucketName, fileName, 7);
		} catch (Exception e){
			logger.error("文件录入异常", e);
		}
		return null;
	}

	/**
	 * 获取文件的共享路径
	 * @param bucketName 桶名
	 * @param fileName 文件名称
	 * @param expires 共享时间限制，默认单位是秒
	 * @return url
	 */
	public String getShareUrl(String bucketName, String fileName, Integer expires) {
		String url = "";
		try{
			if (!getClient().bucketExists(bucketName)) {
				getClient().makeBucket(bucketName);
			}
			url = getClient().presignedGetObject(bucketName, fileName, expires);
		} catch (Exception e){
			logger.error("获取共享路径失败", e);
		}
		return url;
	}

	/**
	 * 删除文件
	 * @param bucketName 桶名
	 * @param fileName 文件名称
	 * @return url
	 */
	public String deleteFile(String bucketName, String fileName) {
		String url = "";
		try{
			if (!getClient().bucketExists(bucketName)) {
				getClient().makeBucket(bucketName);
			}
			getClient().removeObject(bucketName, fileName);
		} catch (Exception e){
			logger.error("删除文件失败", e);
		}
		return url;
	}
}
